extends Node2D


@onready var _game_over_menu: GameOverMenu = $CanvasLayer/GameOverMenu as GameOverMenu
@onready var _enemy_spawner: EntitySpawner = $EnemySpawner as EntitySpawner
@onready var _health_potion_spawner: EntitySpawner = $HealthPotionSpawner as EntitySpawner
@onready var _time_label: Label = $CanvasLayer/TimerUI/TimeLabel as Label
@onready var _ip_label: Label = $CanvasLayer/NetworkUI/IPLabel as Label
@onready var _player_multiplayer_spawner: MultiplayerSpawner = $PlayerMultiplayerSpawner as MultiplayerSpawner
@onready var _player_start_positions: Node2D = $PlayerStartPositions as Node2D


@export var player_scene: PackedScene = preload("res://parts/player/player.tscn")
@export var _time: float = 0.0:
	set(value):
		_time = value
		_time_label.text = str(floor(_time))


var _player_spawn_index: int = 0


func _on_player_died() -> void:
	end_game.rpc()


@rpc("authority", "reliable", "call_local")
func end_game() -> void:
	_game_over_menu.refresh_score(_time)
	_game_over_menu.show()
	_enemy_spawner.stop_timer()
	_health_potion_spawner.stop_timer()
	set_process(false)
	HighscoreManager.set_new_highscore(floori(_time))


func _process(delta: float) -> void:
	_time += delta


func add_player(id: int) -> void:
	_player_multiplayer_spawner.spawn(id)
	
	
func spawn_player(id: int) -> Player:
	var player: Player = player_scene.instantiate() as Player
	player.multiplayer_id = id
	player.name = str(id)
	player.player_name = "Erika {0}".format([ id ])
	#add_child(player)
	player.died.connect(_on_player_died)
	var spawn_marker: Marker2D = _player_start_positions.get_child(_player_spawn_index) as Marker2D
	player.position = spawn_marker.position
	_player_spawn_index = (_player_spawn_index + 1) % _player_start_positions.get_child_count()
	return player


func _ready() -> void:
	_player_multiplayer_spawner.spawn_function = spawn_player
	if multiplayer.is_server():
		show_local_ip_address()
		multiplayer.peer_connected.connect(add_player)
		add_player(1)
	else:
		set_process(false)


func show_local_ip_address() -> void:
	var addresses: Array[String] = []
	for ip: String in IP.get_local_addresses():
		if ip.begins_with("10.") or ip.begins_with("172.16.") or ip.begins_with("192.168."):
			addresses.push_back(ip)
	if not addresses.is_empty():
		_ip_label.text = addresses[0]
